// ignore_for_file: use_build_context_synchronously

import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/my/about_page.dart';
import 'package:encrypt_and_decrypt_files/my/key_management_page.dart';
import 'package:encrypt_and_decrypt_files/my/language_selected_page.dart';
import 'package:encrypt_and_decrypt_files/my/login_page.dart';
import 'package:encrypt_and_decrypt_files/my/member_management_page.dart';
import 'package:encrypt_and_decrypt_files/my/reset_password_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:local_auth/local_auth.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

class MyPage extends StatefulWidget {
  const MyPage({
    super.key,
  });

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);
    pickerColor = themeProvider.mainColor;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: themeProvider.mainColor,
        centerTitle: true,
        title: Text('My'.t(context)),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(
              height: 10,
            ),
            _everyJumpColumn('Account Management'.t(context), () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const ResetPasswordPage(),
                ),
              );
            }),
            const SizedBox(
              height: 5,
            ),
            _everyJumpColumn('Key Management'.t(context), () async {
              _authenticateAndNavigate();
            }),
            const SizedBox(
              height: 5,
            ),
            _everyJumpColumn('MemberShip Management'.t(context), () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MemberManagementPage(),
                ),
              ).then((value) => setState(() {}));
            }),
            const SizedBox(
              height: 5,
            ),
            _everyJumpColumn('language'.t(context), () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const SelectLanguagePage(),
                ),
              ).then((value) => setState(() {}));
            }),
            const SizedBox(
              height: 5,
            ),
            _everyJumpColumn('Theme'.t(context), () {
              showSelectColor();
            }),
            const SizedBox(
              height: 5,
            ),
            _everyJumpColumn('About'.t(context), () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AboutPage(),
                ),
              );
            }),
            const SizedBox(
              height: 5,
            ),
            _everyJumpColumn('Log out'.t(context), logout),
            const SizedBox(
              height: 5,
            ),
          ],
        ),
      ),
    );
  }

  /// One-line jump
  Widget _everyJumpColumn(String title, VoidCallback voidCallBack) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        voidCallBack.call();
      },
      child: Container(
        margin: const EdgeInsets.only(left: 10, right: 10),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: themeProvider.mainColor,
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(title),
            Image.asset(
              'assets/images/home/ic_arrow_right.png',
              width: 14,
              height: 14,
            ),
          ],
        ),
      ),
    );
  }

  void changeColor(Color color) {
    pickerColor = color;
  }

  Color? pickerColor;

  void showSelectColor() {
    showDialog(
      builder: (context) => AlertDialog(
        title: Text('Pick a color!'.t(context)),
        content: SingleChildScrollView(
          child: ColorPicker(
            pickerColor: pickerColor!,
            onColorChanged: changeColor,
          ),
        ),
        actions: <Widget>[
          ElevatedButton(
            child: Text('Got it'.t(context)),
            onPressed: () {
              final themeProvider =
                  Provider.of<ThemeProvider>(context, listen: false);
              themeProvider.setDefaultColor(pickerColor!);
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
      context: context,
    );
  }

  Future<void> _authenticateAndNavigate() async {
    final _localAuth = LocalAuthentication();

    try {
      bool isAuthenticated = await _localAuth.authenticate(
        localizedReason: '请验证您的指纹',
        options: const AuthenticationOptions(stickyAuth: true),
      );

      if (isAuthenticated) {
        // 如果验证成功，跳转到目标页面
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const KeyManagementPage()),
        );
      } else {
        // 验证失败，显示提示
        Fluttertoast.showToast(msg: 'Authentication failure'.t(context));
      }
    } catch (e) {
      Fluttertoast.showToast(msg: 'Authentication failure'.t(context));
    }
  }

  Future<void> logout() async {
    String token = SpUtil.getString('token') ?? '';

    const url = '/logout';
    var response = await DioHttp.of(context).post(url, null, token);

    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      SpUtil.remove('token');
      SpUtil.remove('userModel');
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const LoginPage()),
          (Route<dynamic> route) => false);
    }
  }
}
